const API = require('../api/orc');
const File = require('../utils/operateFile');
const chalk = require("chalk");

/**
 * @param url 裁剪后的图片地址
 * @param ut  usertoken
 * @param uid uid
 * @param clientId clientId
 */
 async function getTxt({url, ut, uid, clientId}) {
  let r1 = await API.getTid({
    params: {
      url,
      ut
    },
    headers: {
      uid,
      clientId,
    }
  });

  if (r1.data.result.code === 0) {
    let tid = r1.data.data.tid;
    console.log(url + "  获取tid成功");
    await getIdentifyResult({ tid, url, ut, uid, clientId });
  } else {
    console.log(url + "  获取tid出错");
  }
}

async function getIdentifyResult({ tid, url, ut, uid, clientId }) {
  let imgName = url.split('/').pop();
  let fileName = imgName.split('.')[0] + '.txt';
  let r2 = await API.getResult({tid});
  let code = r2.data.result.code;
  if (code === 0) {
    let txt = JSON.parse(r2.data.data).originalText;
    console.log(imgName + "  识别成功");
    File.writeFile(`public/txt/${fileName}`, txt).then(err => {
      if (!err) console.log(chalk.yellow(fileName + "  写入成功"));
      if (err) console.log(chalk.red(fileName + "写入失败"));
    })
  } else if (code === 3) {
    console.log(imgName + "  识别中");
    setTimeout(async function (){
      await getIdentifyResult({ tid, url, ut, uid, clientId });
    }, 2000)
  } else {
    // 需重新提交
    console.log(imgName + "  重新提交");
    await getTxt({ url, ut, uid, clientId });
  }
}

module.exports = getTxt;
